import 'dart:convert';

import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/product_stockorder_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/product_stockorder.dart';
import 'package:flutter_admin/pages/odoo/product_stockorder/product_stockorder_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/product_stockorder_supplement/product_stockorder_supplement_edit.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:flutter_admin/utils/helper/save_file_mobile.dart'
    if (dart.library.html) 'package:flutter_admin/utils/helper/save_file_web.dart';
import 'package:http/http.dart' show get;

class ProductStockorderSupplementList extends StatefulWidget {
  ProductStockorderSupplementList({Key? key}) : super(key: key);

  @override
  _ProductStockorderSupplementListState createState() =>
      _ProductStockorderSupplementListState();
}

class _ProductStockorderSupplementListState
    extends State<ProductStockorderSupplementList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ProductStockorder productStockorder = ProductStockorder();
  List<ProductStockorder> selectedList = [];

  DateFormat format = DateFormat('yyyy-MM-dd');
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 160,
            label: '开始日期',
            value: productStockorder.createDateStart,
            lastDate: productStockorder.createDateEnd != '' &&
                    productStockorder.createDateEnd != null
                ? format.parse(productStockorder.createDateEnd!)
                : null,
            onSaved: (v) {
              productStockorder.createDateStart = v;
              setState(() {});
            },
          ),
          CrySelectDate(
            context,
            width: 160,
            label: '结束日期',
            value: productStockorder.createDateEnd,
            firstDate: productStockorder.createDateStart != '' &&
                    productStockorder.createDateStart != null
                ? format.parse(productStockorder.createDateStart!)
                : null,
            onSaved: (v) {
              productStockorder.createDateEnd = v;
              setState(() {});
            },
          ),
          CryInput(
            width: 140,
            label: '补单单号',
            value: productStockorder.stockorderno,
            onSaved: (v) {
              productStockorder.stockorderno = v;
            },
          ),
          CryInput(
            width: 140,
            label: '零件图号',
            value: productStockorder.productCode,
            onSaved: (v) {
              productStockorder.productCode = v;
            },
          ),
          CryInput(
            width: 140,
            label: '零件名称',
            value: productStockorder.productName,
            onSaved: (v) {
              productStockorder.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('补单日期')),
        DataColumn(label: Text('补单单号')),
        DataColumn(label: Text('零件图号')),
        DataColumn(label: Text('零件名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('补单数量')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建时间')),
      ],
      getCells: (m) {
        ProductStockorder productStockorder = ProductStockorder.fromMap(m);
        return [
          DataCell(Text(productStockorder.orderdate ?? '--')),
          DataCell(Text(productStockorder.stockorderno ?? '--')),
          DataCell(Text(productStockorder.productCode ?? '--')),
          DataCell(Text(productStockorder.productName ?? '--')),
          DataCell(Text(productStockorder.productDesc ?? '--')),
          DataCell(Text(productStockorder.orderqty.toString())),
          DataCell(Text(productStockorder.remark ?? '--')),
          DataCell(Text(productStockorder.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(productStockorder.createDate))),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        CryButton(
            label: '导出打印',
            iconData: Icons.print_rounded,
            onPressed: selectedList.length < 1
                ? null
                : () => _createPDF(selectedList)),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  Future<void> _createPDF(List<ProductStockorder> selectedList) async {
    PdfDocument document = PdfDocument();
    document.pageSettings.orientation = PdfPageOrientation.landscape;
    document.pageSettings.margins.all = 50;

    for (var index = 0; index < selectedList.length; index++) {
      var qrCode = selectedList[index].stockorderno! +
          "|" +
          selectedList[index].productCode!;
      List? dataList = [];
      ResponseBodyApi responseBodyApi = await DynamicDataApi.getModels(
          model: "product.stockorderprocess",
          key: 'stockorderno',
          operator: '=',
          val: selectedList[index].stockorderno);
      if (responseBodyApi.success!) {
        dataList = responseBodyApi.data;
      }
      var res = await ProductStockorderOdooApi.getBarcode(qrCode);
      PdfImage image = PdfBitmap.fromBase64String(res.data);
      //Draws the image to the PDF page
      PdfPage page = document.pages.add();
      PdfGraphics graphics = page.graphics;

      PdfFont font = PdfCjkStandardFont(PdfCjkFontFamily.sinoTypeSongLight, 20);
      String title = '中天宽带技术有限公司（补单）';
      Size size = font.measureString(title);
      graphics.drawString(title, font,
          brush: PdfBrushes.black,
          bounds: Rect.fromLTWH(graphics.clientSize.width / 2 - size.width / 2,
              10, graphics.clientSize.width, 50));

      // 这里应该是条形码
      String test = '生产单号：';
      graphics.drawString(
          test, PdfCjkStandardFont(PdfCjkFontFamily.sinoTypeSongLight, 12),
          brush: PdfBrushes.black,
          bounds: Rect.fromLTWH(0, 60, graphics.clientSize.width, 20));
      // PdfBrush solidBrush = PdfSolidBrush(PdfColor(126, 151, 173));
      page.graphics.drawImage(image, Rect.fromLTWH(60, 40, 250, 70));

      // Rect bounds = Rect.fromLTWH(0, 160, graphics.clientSize.width, 30);
      // graphics.drawRectangle(brush: solidBrush, bounds: bounds);

      PdfGrid grid = PdfGrid();

      grid.columns.add(count: 8);

      grid.headers.add(2);
      PdfGridRow headerTop = grid.headers[0];
      headerTop.cells[0].value = '零件编码';
      headerTop.cells[1].value = selectedList[index].productCode;
      headerTop.cells[2].value = '零件名称';
      headerTop.cells[3].value = selectedList[index].productName;
      headerTop.cells[4].value = '规格型号';
      headerTop.cells[5].value = selectedList[index].productDesc;
      headerTop.cells[6].value = '数量';
      headerTop.cells[7].value = selectedList[index].orderqty.toString();
      PdfGridCellStyle headerTopStyle = PdfGridCellStyle();
      headerTopStyle.borders.all = PdfPen(PdfColor(126, 151, 173));
      headerTopStyle.backgroundBrush = PdfSolidBrush(PdfColor(126, 151, 173));
      headerTopStyle.textBrush = PdfBrushes.white;
      headerTopStyle.font = PdfCjkStandardFont(
          PdfCjkFontFamily.sinoTypeSongLight, 14,
          style: PdfFontStyle.regular);
      for (int i = 0; i < headerTop.cells.count; i++) {
        if (i == 0 || i == 1) {
          headerTop.cells[i].stringFormat = PdfStringFormat(
              alignment: PdfTextAlignment.left,
              lineAlignment: PdfVerticalAlignment.middle);
        } else {
          headerTop.cells[i].stringFormat = PdfStringFormat(
              alignment: PdfTextAlignment.right,
              lineAlignment: PdfVerticalAlignment.middle);
        }
        headerTop.cells[i].style = headerTopStyle;
      }

      PdfGridRow header = grid.headers[1];
      header.cells[0].value = '序号';
      header.cells[1].value = '工序名称';

      PdfGridCellStyle headerStyle = PdfGridCellStyle();
      headerStyle.borders.all = PdfPen(PdfColor(126, 151, 173));
      headerStyle.backgroundBrush = PdfSolidBrush(PdfColor(126, 151, 173));
      headerStyle.textBrush = PdfBrushes.white;
      headerStyle.font = PdfCjkStandardFont(
          PdfCjkFontFamily.sinoTypeSongLight, 14,
          style: PdfFontStyle.regular);

      for (int i = 0; i < header.cells.count; i++) {
        if (i == 0 || i == 1) {
          header.cells[i].stringFormat = PdfStringFormat(
              alignment: PdfTextAlignment.left,
              lineAlignment: PdfVerticalAlignment.middle);
        } else {
          header.cells[i].stringFormat = PdfStringFormat(
              alignment: PdfTextAlignment.right,
              lineAlignment: PdfVerticalAlignment.middle);
        }
        header.cells[i].style = headerStyle;
      }
      if (dataList!.length > 0) {
        for (int i = 0; i < dataList.length; i++) {
          PdfGridRow row = grid.rows.add();
          row.cells[0].value = (i + 1).toString();
          row.cells[1].value = dataList[i]['process_id'][1];
        }
      }

      grid.style.cellPadding =
          PdfPaddings(left: 2, right: 2, top: 2, bottom: 2);

      PdfGridCellStyle cellStyle = PdfGridCellStyle();
      cellStyle.borders.all = PdfPens.white;
      cellStyle.borders.bottom = PdfPen(PdfColor(217, 217, 217), width: 0.70);
      cellStyle.font =
          PdfCjkStandardFont(PdfCjkFontFamily.sinoTypeSongLight, 12);
      cellStyle.textBrush = PdfSolidBrush(PdfColor(131, 130, 136));

      for (int i = 0; i < grid.rows.count; i++) {
        PdfGridRow row = grid.rows[i];
        for (int j = 0; j < row.cells.count; j++) {
          row.cells[j].style = cellStyle;
          if (j == 0 || j == 1) {
            row.cells[j].stringFormat = PdfStringFormat(
                alignment: PdfTextAlignment.left,
                lineAlignment: PdfVerticalAlignment.middle);
          } else {
            row.cells[j].stringFormat = PdfStringFormat(
                alignment: PdfTextAlignment.right,
                lineAlignment: PdfVerticalAlignment.middle);
          }
        }
      }
      // PdfLayoutFormat layoutFormat =
      //     PdfLayoutFormat(layoutType: PdfLayoutType.paginate);

      // PdfLayoutResult gridResult = grid.draw(
      //     page: page,
      //     bounds: Rect.fromLTWH(0, bounds.top + 20, graphics.clientSize.width,
      //         graphics.clientSize.height - 100),
      //     format: layoutFormat)!;
      grid.draw(
          page: page,
          bounds: Rect.fromLTWH(0, 110, graphics.clientSize.width,
              graphics.clientSize.height - 150));
      // document.pages.add()
    }
    List<int> bytes = document.save();
    await FileSaveHelper.saveAndLaunchFile(bytes, '补单.pdf');

    document.dispose();
  }

  _edit(ProductStockorder? productStockorder) async {
    if (productStockorder != null) {
      productStockorder.processList = [];
      ResponseBodyApi responseBodyApi = await DynamicDataApi.getModels(
          model: "product.stockorderprocess",
          key: 'stockorderno',
          val: productStockorder.stockorderno);
      if (responseBodyApi.success!) {
        for (Map map in responseBodyApi.data) {
          productStockorder.processList!.add(map['process_id'][0]);
        }
      }
    }
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductStockorderSupplementEdit(
          productStockorder: productStockorder,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _reset() {
    productStockorder = ProductStockorder();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    productStockorder.isSupplement = '1';
    ResponseBodyApi responseBodyApi = await ProductStockorderOdooApi.page(
        data: {"page": page, "domainList": productStockorder.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<ProductStockorder> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await ProductStockorderOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductStockorderDialog(),
      ),
    ).then((v) {
      if (v != null) {
        productStockorder = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ProductStockorder>((e) => ProductStockorder.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
